package org.biubiu0002.baiblog.im.service.impl;

import com.alibaba.fastjson.JSON;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.biubiu0002.baiblog.im.constants.MessageConstants;
import org.biubiu0002.baiblog.im.dto.message.Message;
import org.biubiu0002.baiblog.im.dto.message.MessageNotification;
import org.biubiu0002.baiblog.im.service.NotifyService;
import org.biubiu0002.baiblog.im.session.ServerSession;
import org.biubiu0002.baiblog.im.session.SessionMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: biubiu0002
 * @Date: 2022/12/22 13:08
 **/
@Service
public class NotifyServiceImpl implements NotifyService {

    @Resource
    private SessionMap sessionMap;

    @Override
    public void notify(int type, Object object) {

    }

    @Override
    public void notifyGroup(int type, List<String> uidList, String groupUid, String content) {
        Message message = new Message();
        message.setType(MessageConstants.MessageType.NOTIFICATION);
        MessageNotification messageNotification = new MessageNotification();
        messageNotification.setType(type);
        messageNotification.setSessionRole(MessageConstants.MessageSessionRoleType.GROUP_CHAT);
        messageNotification.setContent(content);
        messageNotification.setTo(groupUid);
        messageNotification.setTime(System.currentTimeMillis());
        message.setMessageNotification(messageNotification);
        List<ServerSession> sessionListByUidList = sessionMap.getSessionListByUidList(uidList);
        for (ServerSession session : sessionListByUidList) {
            TextWebSocketFrame frame = new TextWebSocketFrame(JSON.toJSONString(message));
            //writeAndFlush会释放object?
            session.getChannel().writeAndFlush(frame);
        }
    }

}
